import API from '../../http/api.js'
import G from '../../general/generateData.js'
import async from "../../general/async.js"
function D() {
    //异步处理变同步还有点问题。
}
D.prototype = new async()
D.prototype.constructor = D;
D.prototype.create = function (dataSet, path = undefined) {

    let self = this;
    let DataResult = {};
    let asyncTaskCount = Object.keys(dataSet).length;
    if (asyncTaskCount < 0) {
        this.waitTask = 0
    }
    this.waitTask += asyncTaskCount;
    for (let o in dataSet) {
        DataResult[o] = undefined
        let result = Object.assign({}, dataSet[o])
        if ('source' in result) {
            result.source += result.source.indexOf('?') > -1 ? "&timestamp=" : "?timestamp=" + Date.parse(new Date()).toString()
            API.getContext(result.source).then(res => {
                if (res.status == 200) {
                    DataResult[o] = res.data
                } else {
                    throw new Error(`[getdata.js] access ${result.source} error ${res.status}`)
                }
                --this.waitTask
            }).catch(error => {
                --this.waitTask
                throw error
            })
        }
        else {
            if ('original' in result) {
                DataResult[o] = result['original']
                --this.waitTask
            }
            else {
                result.model += result.model.indexOf('?') > -1 ? "&timestamp=" : "?timestamp=" + Date.parse(new Date()).toString()
                API.getContext(result.model).then(res => {
                    let model = Object.assign({}, res.data)
                    let count = ('count' in result) ? result.count : 1
                    if (count > 1) {
                        DataResult[o] = []
                        for (let pos = 1; pos <= count; ++pos) {
                            DataResult[o].push(G.create(model))
                        }
                    } else {
                        DataResult[o] = G.create(model)
                    }
                    --this.waitTask
                })
            }
        }
    }
    this.target = DataResult
    return this
}

const Data = new D()
export { Data, D }